package com.bobo.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bobo.rbac.auth.utils.JwtUtils;
import com.bobo.rbac.auth.utils.ResponseResult;
import com.bobo.rbac.domain.User;
import com.bobo.rbac.mapper.UserMapper;
import com.bobo.rbac.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;

/**
 * @description:
 * @author: BOBO
 * @time: 2022/7/24 18:08
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    RedisTemplate  redisTemplate;
    @Override
    public ResponseResult login(User formUser) {

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(formUser.getUsername(),formUser.getPassword());
        //调用
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);

        //登录成功，
        String jwt = JwtUtils.createToken(formUser.getUsername(),30);

        //把登录人角色信息存入redis
        Collection<? extends GrantedAuthority> authorities = authenticate.getAuthorities();
        redisTemplate.opsForValue().set("login:"+formUser.getUsername(),authorities);

        //把该用户的权限信息存入redis
        HashMap<String, String> map = new HashMap<>();
        map.put("token",jwt);

        return ResponseResult.ok(map);

    }

    @Override
    public ResponseResult loginByPhone(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
         queryWrapper.eq("phone", user.getPhone());
        User dbUser = userMapper.selectOne(queryWrapper);
         return    this.login(dbUser);
      /*  if(null==dbUser){
          return   ResponseResult.fail(300,"无此账户");
        }
//登录成功，
        String jwt = JwtUtils.createToken(dbUser.getUsername(),30);
        //把登录人角色信息存入redis
        List<String> roleList = userMapper.getRole(dbUser.getId());
        List<SimpleGrantedAuthority> authorities = roleList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());

        redisTemplate.opsForValue().set("login:"+dbUser.getUsername(),authorities);

        //把该用户的权限信息存入redis
        HashMap<String, String> map = new HashMap<>();
        map.put("token",jwt);
        return ResponseResult.ok(map);*/
    }
}
